import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { ElMessage, ElNotification } from 'element-plus'
import { useApiStore } from '@/stores'
import type { ApiResponse } from '@/types'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 增加请求计数
    const apiStore = useApiStore()
    apiStore.startRequest()
    
    // 添加请求时间戳
    config.metadata = { startTime: Date.now() }
    
    // 可以在这里添加token等认证信息
    // const token = localStorage.getItem('token')
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    
    return config
  },
  (error) => {
    const apiStore = useApiStore()
    apiStore.endRequest()
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const apiStore = useApiStore()
    apiStore.endRequest()
    
    // 计算请求耗时
    const startTime = response.config.metadata?.startTime
    if (startTime) {
      const duration = Date.now() - startTime
      console.log(`API请求耗时: ${duration}ms - ${response.config.url}`)
    }
    
    return response
  },
  (error: AxiosError) => {
    const apiStore = useApiStore()
    apiStore.endRequest()
    
    console.error('Response error:', error)
    
    // 记录错误到状态管理
    const errorInfo = {
      message: '',
      url: error.config?.url,
      status: error.response?.status
    }
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          errorInfo.message = data?.message || '请求参数错误'
          ElMessage.error(errorInfo.message)
          break
        case 401:
          errorInfo.message = '未授权访问'
          ElMessage.error(errorInfo.message)
          // 可以在这里处理登录跳转
          break
        case 403:
          errorInfo.message = '访问被拒绝'
          ElMessage.error(errorInfo.message)
          break
        case 404:
          errorInfo.message = '请求的资源不存在'
          ElMessage.error(errorInfo.message)
          break
        case 413:
          errorInfo.message = '文件大小超出限制'
          ElMessage.error(errorInfo.message)
          break
        case 429:
          errorInfo.message = '请求过于频繁，请稍后重试'
          ElMessage.warning(errorInfo.message)
          break
        case 500:
          errorInfo.message = '服务器内部错误'
          ElMessage.error(errorInfo.message)
          ElNotification({
            title: '服务器错误',
            message: '服务器遇到了问题，请稍后重试或联系管理员',
            type: 'error',
            duration: 5000
          })
          break
        case 502:
          errorInfo.message = '网关错误'
          ElMessage.error(errorInfo.message)
          break
        case 503:
          errorInfo.message = '服务暂时不可用'
          ElMessage.error(errorInfo.message)
          break
        case 504:
          errorInfo.message = '请求超时'
          ElMessage.error(errorInfo.message)
          break
        default:
          errorInfo.message = data?.message || '网络错误，请稍后重试'
          ElMessage.error(errorInfo.message)
      }
    } else if (error.request) {
      errorInfo.message = '网络连接失败，请检查网络设置'
      ElMessage.error(errorInfo.message)
      ElNotification({
        title: '网络错误',
        message: '无法连接到服务器，请检查网络连接',
        type: 'error',
        duration: 5000
      })
    } else {
      errorInfo.message = '请求配置错误'
      ElMessage.error(errorInfo.message)
    }
    
    // 记录错误到状态管理
    apiStore.addError(errorInfo)
    
    return Promise.reject(error)
  }
)

// 通用请求方法
export const request = {
  get<T = any>(url: string, config?: any): Promise<ApiResponse<T>> {
    return api.get(url, config).then(res => res.data)
  },
  
  post<T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
    return api.post(url, data, config).then(res => res.data)
  },
  
  put<T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
    return api.put(url, data, config).then(res => res.data)
  },
  
  delete<T = any>(url: string, config?: any): Promise<ApiResponse<T>> {
    return api.delete(url, config).then(res => res.data)
  }
}

// 文件上传方法
export const uploadFile = (
  url: string, 
  file: File, 
  onProgress?: (progress: number) => void
): Promise<ApiResponse> => {
  const formData = new FormData()
  formData.append('file', file)
  
  return api.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        onProgress(progress)
      }
    }
  }).then(res => res.data)
}

// 批量文件上传方法
export const uploadFiles = (
  url: string, 
  files: File[], 
  onProgress?: (progress: number) => void
): Promise<ApiResponse> => {
  const formData = new FormData()
  files.forEach(file => {
    formData.append('files', file)
  })
  
  return api.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (onProgress && progressEvent.total) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        onProgress(progress)
      }
    }
  }).then(res => res.data)
}

export default api